package com.ygqh.baby.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.po.YgProductImages;

public class InternetWormUtils {

	/**
	 * 获取视频地址
	 * 
	 * @Title: getVideoPath
	 * @param path
	 *            入参
	 * @return String 返回类型
	 * @author （guohao）
	 * @throws
	 * @date 2017年9月28日 上午10:24:09
	 * @version V1.0
	 */
	public static String getVideoPath(String path) {
		String str = null;
		try {
			URL url = new URL(path);
			HttpURLConnection uc = (HttpURLConnection) url.openConnection();
			BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
			while ((str = br.readLine()) != null) {
				if (str.indexOf("videoSrc") != -1) {
					int startIndex = str.indexOf(":") + 2;
					int endIndex = str.indexOf("?");
					if (startIndex > 1 && endIndex > 0) {
						str = str.substring(startIndex, endIndex);
					}
					break;
				}
			}
			br.close();
			uc.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 获取天猫商品详情图链接
	 * 
	 * @Title: getTmallImgPath
	 * @param path
	 *            入参
	 * @return String 返回类型
	 * @author （guohao）
	 * @throws
	 * @date 2017年9月28日 下午3:33:45
	 * @version V1.0
	 */
	public static YgProduct getTmallImgPath(String path) {
		HttpURLConnection uc = null;
		BufferedReader br = null;
		String str = null;
		YgProduct product = new YgProduct();
		List<YgProductImages> images = new ArrayList<YgProductImages>();
		String detailImgs = "";
		try {
			URL url = new URL(path);
			uc = (HttpURLConnection) url.openConnection();
			br = new BufferedReader(new InputStreamReader(uc.getInputStream(), "GBK"));

			//System.out.println(br.toString());
			Long sortNum = 1L;
			while ((str = br.readLine()) != null) {
				int i = str.indexOf("aria-label=\"商品主图\"");
				int j = str.indexOf("aria-label=\"商品详情图\"");
				if (i > 0) {
					Boolean isMain = sortNum == 1 ? true : false;
					String imgPath = getTmallImgPath(str, "(src|SRC)=(\"|\')(.*?)(\"|\')");
					imgPath=imgPath.replace("_640x640Q50s50.jpg", "");
					YgProductImages img = new YgProductImages(imgPath, isMain, sortNum);
					images.add(img);
					//System.out.println("主图 ====== " + imgPath);
					sortNum++;
				}
				if (j > 0) {
					String imgPath = getTmallImgPath(str, "(data-ks-lazyload)=(\"|\')(.*?)(\"|\')");
					if (!imgPath.startsWith("https://gw.alicdn.com")) {
						detailImgs += imgPath + ",";
					}
					//System.out.println("详情图 ====== " + imgPath);
				}
			}
			if (StringUtil.isNotBlank(detailImgs)) {
				detailImgs = detailImgs.substring(0, detailImgs.lastIndexOf(","));
			}
			product.setProductImages(images);
			product.setDetailImagePath(detailImgs);

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (uc != null)
				uc.disconnect();
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println(product.toString());
		return product;
	}

	public static String getTaoBaoImgPath(String path) {
		HttpURLConnection uc = null;
		BufferedReader br = null;
		String str = null;
		YgProduct product = new YgProduct();
		List<YgProductImages> images = new ArrayList<YgProductImages>();
		String detailImgs = "";
		try {
			URL url = new URL(path);
			uc = (HttpURLConnection) url.openConnection();
			br = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
			StringBuffer buffer = new StringBuffer();
			System.out.println(br.toString());
			while ((str = br.readLine()) != null) {
				buffer.append(str);
			}
			if (StringUtil.isNotBlank(detailImgs)) {
				detailImgs = detailImgs.substring(0, detailImgs.lastIndexOf(","));
			}
			product.setProductImages(images);
			product.setDetailImagePath(detailImgs);
			System.out.println(buffer.toString());

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (uc != null)
				uc.disconnect();
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return str;
	}

	private static String getTmallImgPath(String str, String reg) {

		String imgpath = null;
		System.out.println(str);
		Pattern p_img = Pattern.compile("<(img|IMG)(.*?)(/>|></img>|>)");
		Matcher m_img = p_img.matcher(str);
		boolean result_img = m_img.find();
		if (result_img) {
			// while (result_img) {
			// 获取到匹配的<img />标签中的内容
			String str_img = m_img.group(2);
			// 开始匹配<img />标签中的src
			Pattern p_src = Pattern.compile(reg);
			Matcher m_src = p_src.matcher(str_img);
			if (m_src.find()) {
				imgpath = m_src.group(3);
			}
			// 匹配content中是否存在下一个<img />标签，有则继续以上步骤匹配<img />标签中的src
			// result_img = m_img.find();
			// System.out.println(result_img);
			// }
		}
		return imgpath;

	}

	private static String getTaoBaoImgPath(String str, String reg) {

		String imgpath = null;
		System.out.println(str);
		Pattern p_img = Pattern.compile("<(img|IMG)(.*?)(/>|></img>|>)");
		Matcher m_img = p_img.matcher(str);
		boolean result_img = m_img.find();
		if (result_img) {
			// while (result_img) {
			// 获取到匹配的<img />标签中的内容
			String str_img = m_img.group(2);
			// 开始匹配<img />标签中的src
			Pattern p_src = Pattern.compile(reg);
			Matcher m_src = p_src.matcher(str_img);
			if (m_src.find()) {
				imgpath = m_src.group(3);
			}
			// 匹配content中是否存在下一个<img />标签，有则继续以上步骤匹配<img />标签中的src
			// result_img = m_img.find();
			// System.out.println(result_img);
			// }
		}
		return imgpath;

	}

	// 下载视频方法
	private static void getDondow(String url, String pathName) throws Exception {
		URL ul = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
		BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
		FileOutputStream bs = new FileOutputStream(pathName);
		System.out.println("文件大约：" + (conn.getContentLength() / 1024) + "K");
		byte[] by = new byte[1024];
		int len = 0;
		while ((len = bi.read(by)) != -1) {
			bs.write(by, 0, len);
		}
		bs.close();
		bi.close();
	}

	public static void main(String[] args) {
		YgProduct tmallImgPath = getTmallImgPath("https://detail.m.tmall.com/item.htm?id=564728069511");
	}
}